package myJs.user.soft.preprocess

import myJs.Implicits._
import myJs.cps._
import myJs.myPkg.reactHookForm._
import myJs.tool.Tool
import myJs.tool.Tool._

import scala.scalajs.js

import japgolly.scalajs.react.vdom.all._
import japgolly.scalajs.react._
import japgolly.scalajs.react.React.Fragment
import japgolly.scalajs.react.util.EffectCatsEffect._
import myJs.myPkg.Hooks._
import cats.effect._
import myJs.Implicits._
import myJs.Utils._

/** Created by yz on 3/11/2020
  */
object InputGroupCp {

  case class Props(
      name: String,
      value: String,
      label: String,
      show: Boolean = true,
      questionInfo: String = "",
      registerOptions: RegisterOptions = RegisterOptions(),
      onChange: String => SyncIO[Unit] = v => SyncIO.unit
  ) {
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>
    useEffect(
      SyncIO {
        Tool.popover
      }.void,
      List()
    )
    val formState = ReactHookForm.useFormState(options =
      UseFormStateOptions(
        name = props.name
      )
    )

    val hasErrorCls = if (formState.errors.deepDefinedAt(props.name)) "has-error" else ""

    val displayMod = if (props.show) display.block else display.none
    div(
      displayMod,
      className := s"form-group col-sm-12 ${hasErrorCls}",
      label(
        className := "",
        s"${props.label}",
        if (props.questionInfo.nonBlank) {
          span(
            className := "",
            a(
              `type` := "button",
              className := "selfQuestion",
              title := messages("note"),
              dataContainer := "body",
              dataToggle := "popover",
              dataHtml := "true",
              dataPlacement := "left",
              dataContent := props.questionInfo,
              i(className := "fa fa-question-circle-o")
            )
          )
        } else EmptyVdom,
        ":"
      ),
      div(
        className := "input-group",
        PureInputCp.Props(name = s"${props.name}Show", value = s"${props.show}", `type` = "hidden").render,
        PureInputCp
          .Props(
            name = props.name,
            value = props.value,
            registerOptions = props.registerOptions,
            onChange = props.onChange,
            showValidate = false
          )
          .render,
        span(className := "input-group-addon", "%")
      ),
      if (formState.errors.deepDefinedAt(props.name)) {
        small(className := "help-block", formState.errors.deepGet(props.name).message)
      } else EmptyVdom
    )
  }

}
